package cn.org.timespace.ons.util.json;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.util.Collection;
import java.util.HashSet;

import org.apache.log4j.Logger;

public class JSONUtil
{
	private final static Logger log = Logger.getLogger(JSONUtil.class);

	public static <T> T copyProperties(JSONObject json, Class<T> clz)
	{
		try
		{
			T obj = clz.newInstance();
			BeanInfo info = Introspector.getBeanInfo(obj.getClass());
			PropertyDescriptor[] ds = info.getPropertyDescriptors();
			for (PropertyDescriptor d : ds)
			{
				System.out.println(json.get(d.getName()));
				d.getWriteMethod().invoke(obj, json.get(d.getName()));
			}
			return obj;
		} catch (Exception e)
		{
			log.error(e.getMessage());
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	public static <T> Collection<T> getCollectionFromArray(JSONArray arr, Class<T> clz)
	{
		try
		{
			Collection c = new HashSet();
			for (int i = 0; i < arr.length(); i++)
			{
				if (clz == Integer.class)
				{	log.debug("JsonUtil返回Integer");
					c.add(arr.getInt(i));
				}
				if (clz == String.class)
				{
					log.debug("JsonUtil返回String");
					c.add(arr.getString(i));
				}
				if (clz==Long.class)
				{
					log.debug("JsonUtil返回Long");
					c.add(arr.getLong(i));
				}
			}
			return c;
		} catch (Exception e)
		{
			log.error(e.getMessage());
		}
		return null;
	}
}
